package net.vistiyos.android;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import net.vistiyos.R;
import net.vistiyos.exception.GetDataSerieException;
import net.vistiyos.exception.NotSignInException;
import net.vistiyos.modelo.Capitulo;
import net.vistiyos.modelo.Serie;
import net.vistiyos.modelo.Usuario;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MyPageAdapterSerie extends PagerAdapter implements OnItemClickListener{
	
	private SerieActivity padre;
	private Serie serie;
	
	public MyPageAdapterSerie(SerieActivity padre,Serie serie){
		this.padre = padre;
		this.serie = serie; 
	}

	public int getCount() {
        return serie.getTemporadas()+1;
    }

    public Object instantiateItem(View collection, int position) {

        LayoutInflater inflater = (LayoutInflater) collection.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = null;
        	if(position==0){
        		try {
        			view = inflater.inflate(R.layout.ficha_serie, null);
        			TextView sinopsis = (TextView) view.findViewById(R.id.sinopsis);
        			String sinopsisT = serie.getSinopsis();
        			String[] sinopsisA = sinopsisT.split(" ");
        			String sinopsisF = "";
        			int j = 1;
        			for(int i=0;i<sinopsisA.length;i++){
        				sinopsisF+=sinopsisA[i]+" ";
        				if(sinopsisF.length() >= (j*70)){
        					sinopsisF+="\n";
        					j++;
        				}
        			}
        			sinopsis.setText(sinopsis.getText().toString()+"\n"+sinopsisF);
        			ImageView imagen = (ImageView)view.findViewById(R.id.poster);
        			imagen.setImageBitmap(new ObtenerDatos(serie).execute().get());
        		} catch (InterruptedException e) {
        			e.printStackTrace();
        		} catch (ExecutionException e) {
        			e.printStackTrace();
        		}
        	}
        	if(position >0 && position<=serie.getTemporadas()){
        			view = inflater.inflate(R.layout.temporada, null);
        			ArrayList<Capitulo> temporada = serie.getTemporada(position);
        			CapituloAdapter capitulos = new CapituloAdapter(temporada);
        			ListView lstOpciones = (ListView)view.findViewById(R.id.capitulos);
        			TextView temporadaT = (TextView) view.findViewById(R.id.temporada);
                	temporadaT.setText("Temporada "+position);
                	lstOpciones.setAdapter(capitulos);
        	}

        ((ViewPager) collection).addView(view, 0);

        return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);

    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);

    }

    @Override
    public Parcelable saveState() {
        return null;
    }
    
    class CapituloAdapter extends ArrayAdapter<Capitulo> {
    	
    	private ArrayList<Capitulo> lista;
		CapituloAdapter(ArrayList<Capitulo> lista) {
			super(padre, R.layout.row_capitulo, lista);
			this.lista = lista;
		}
		
		public View getView(int position, View convertView,ViewGroup parent) {
			LayoutInflater inflater=padre.getLayoutInflater();
			final int indice = position;
			View row=inflater.inflate(R.layout.row_capitulo,parent,false);
			TextView label=(TextView)row.findViewById(R.id.label);
			Capitulo actual = lista.get(position);
			label.setText(actual.getTemporada()+"x"+actual.getCapitulo()+" - "+actual.getTitulo());
			ToggleButton visto = (ToggleButton) row.findViewById(R.id.visto);
			visto.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					new MarcarVisto(CapituloAdapter.this.lista.get(indice)).execute();
					new RecargarNotificaciones().execute();
				}
				
			});
			if(lista.get(position).isVisto())
				visto.toggle();
			return(row);
		}
    }
    
    private class ObtenerDatos extends AsyncTask< Void, Void, Bitmap>{
	
		private Serie serie;
	
		public ObtenerDatos(Serie serie){
			this.serie = serie;
		}
		
		@Override
		protected Bitmap doInBackground(Void... params) {
			try{
    			HttpURLConnection conn = (HttpURLConnection) serie.getPoster().getURL().openConnection();
    			conn.connect();
    			return BitmapFactory.decodeStream(conn.getInputStream());
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
			return null;
		}
	}

    private class MarcarVisto extends AsyncTask< Void, Void, Void>{
	
    	private Capitulo capitulo;

    	public MarcarVisto(Capitulo capitulo){
    		this.capitulo = capitulo;
    	}
	
    	@Override
    	protected Void doInBackground(Void... params) {
    		try {
    			this.capitulo.toggleVisto();
    		} catch (MalformedURLException e) {
    			e.printStackTrace();
    		} catch (NotSignInException e) {
    			e.printStackTrace();
    		} catch (GetDataSerieException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    }
    
    private class RecargarNotificaciones extends AsyncTask< Void, Void, Void>{
	
    	@Override
    	protected Void doInBackground(Void... params) {
    		try {
				Usuario.obtenerNotificaciones();
			} catch (NotSignInException e) {
				e.printStackTrace();
			}
    		return null;
    	}
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	}

}
